package com.qys.livesMall.app.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qys.livesMall.app.user.mapper.H2AppUserBankMapper;
import com.qys.livesMall.app.user.model.dto.app.AppUserBankDTO;
import com.qys.livesMall.app.user.model.dto.sys.SysAppUserSaveDTO;
import com.qys.livesMall.app.user.model.entity.H2AppUserBank;
import com.qys.livesMall.app.user.service.IH2AppUserBankService;
import com.qys.livesMall.common.constants.Constants;
import com.qys.livesMall.common.exception.QysException;
import com.qys.livesMall.common.utils.MessageUtils;
import com.qys.livesMall.framework.utils.SecurityUtils;
import com.qys.livesMall.app.user.model.dto.sys.QueryUserBankCardDTO;
import com.qys.livesMall.app.user.model.vo.sys.UserBankCardVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户银行卡信息 服务实现类
 * </p>
 *
 * @author dp
 * @since 2023-04-27
 */
@Service
@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class H2AppUserBankServiceImpl extends ServiceImpl<H2AppUserBankMapper, H2AppUserBank> implements IH2AppUserBankService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void bindingBankInfo(AppUserBankDTO userBankDTO) {
        log.info("保存用户银行卡信息: {},用户id:{}", userBankDTO, SecurityUtils.getUserId());
        if (StringUtils.isBlank(userBankDTO.getId())&&StringUtils.isBlank(userBankDTO.getBankNo())){
            throw new QysException(MessageUtils.message("please.print.bank.no"));
        }
        H2AppUserBank h2AppUserBank = new H2AppUserBank();
        if (StringUtils.isNotBlank(userBankDTO.getBankNo())) {
            if (userBankDTO.getType() == 0 && !StringUtils.isNumeric(userBankDTO.getBankNo())) {
                throw new QysException(MessageUtils.message("only.number"));
            }
            LambdaQueryWrapper<H2AppUserBank> wrapper = Wrappers.<H2AppUserBank>lambdaQuery()
                    .eq(H2AppUserBank::getBankNo, userBankDTO.getBankNo())
                    .eq(H2AppUserBank::getType, userBankDTO.getType())
                    .last("limit 1");
            h2AppUserBank = getOne(wrapper);
            if (h2AppUserBank != null && !Objects.equals(h2AppUserBank.getId(), userBankDTO.getId())) {
                throw new QysException(MessageUtils.message("usdt.address.is.exist"));
            }
        }
        if (h2AppUserBank==null){
            h2AppUserBank=new H2AppUserBank();
        }
        BeanUtils.copyProperties(userBankDTO, h2AppUserBank);
        h2AppUserBank.setUserName(userBankDTO.getBankUserName());
        saveOrUpdate(h2AppUserBank);
    }

    @Override
    public List<H2AppUserBank> queryBankByTypeAndUserId(Byte type, Long userId, String usdtType) {
        LambdaQueryWrapper<H2AppUserBank> wrapper = Wrappers.<H2AppUserBank>lambdaQuery()
                .eq(H2AppUserBank::getType, type)
                .eq(H2AppUserBank::getDeleted, Constants.YesNoInt.NO)
                .eq(H2AppUserBank::getUserId, userId);
        if (StringUtils.isNotBlank(usdtType)) {
            wrapper.eq(H2AppUserBank::getUsdtType, usdtType);
        }
        List<H2AppUserBank> result=baseMapper.selectList(wrapper);
        if (type.intValue()==0 && CollectionUtils.isNotEmpty(result)){
            for (H2AppUserBank appUserBank:result){
                if (appUserBank.getBankNo().length()> 4 && null != appUserBank.getBankNo() ){
                    String str = appUserBank.getBankNo().substring(appUserBank.getBankNo().length() - 4);
                    appUserBank.setBankNo("************"+str);
                }
            }
        }
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(SysAppUserSaveDTO sysAppUserSaveDTO, String userId) {
        //银行卡
        if (StringUtils.isNotBlank(sysAppUserSaveDTO.getBankNo())) {
            if (!StringUtils.isNumeric(sysAppUserSaveDTO.getBankNo())) {
                throw new QysException(MessageUtils.message("only.number"));
            }

            H2AppUserBank h2AppUserBank = new H2AppUserBank();
            h2AppUserBank.setBankName(sysAppUserSaveDTO.getBankName());
            h2AppUserBank.setBankNo(sysAppUserSaveDTO.getBankNo());
            h2AppUserBank.setCardType((byte) 0);
            h2AppUserBank.setType((byte) 0);
            h2AppUserBank.setUserName(sysAppUserSaveDTO.getBankUserName());
            h2AppUserBank.setUserId(userId);
            baseMapper.insert(h2AppUserBank);
        }

        //USDT
        if (StringUtils.isNotBlank(sysAppUserSaveDTO.getUsdtAddress())) {
            H2AppUserBank h2AppUserBank = new H2AppUserBank();
            h2AppUserBank.setBankNo(sysAppUserSaveDTO.getUsdtAddress());
            h2AppUserBank.setType((byte) 1);
            h2AppUserBank.setUsdtType(sysAppUserSaveDTO.getNetworkProtocols());
            h2AppUserBank.setUserId(userId);
            baseMapper.insert(h2AppUserBank);
        }
    }

    @Override
    public void delete(String id) {
        H2AppUserBank bank=baseMapper.selectById(id);
        bank.setDeleted(Constants.YesNoInt.YES);
        baseMapper.updateById(bank);
    }

    @Override
    public Page<UserBankCardVO> selectAll(QueryUserBankCardDTO dto) {
        Page<UserBankCardVO> page = new Page<>(dto.getPageNum(), dto.getPageSize());
        page = baseMapper.selectAll(page, dto);
        return page;
    }

    @Override
    public List<String> listByBankNo(List<String> userIds, String bankNo) {
        LambdaQueryWrapper<H2AppUserBank> wrapper = Wrappers.<H2AppUserBank>lambdaQuery();
        wrapper.select(H2AppUserBank::getUserId);
        if (CollectionUtils.isNotEmpty(userIds)){
            wrapper.in(H2AppUserBank::getUserId,userIds);
        }
        if (StringUtils.isNotBlank(bankNo)){
            wrapper.likeRight(H2AppUserBank::getBankNo,bankNo);
        }
        wrapper.eq(H2AppUserBank::getDeleted,0);
        wrapper.eq(H2AppUserBank::getType,1);
        List<H2AppUserBank> list=list(wrapper);
        return list==null?new ArrayList<>():list.stream().map(H2AppUserBank::getUserId).collect(Collectors.toList());
    }

    @Override
    public List<H2AppUserBank> listByUserIds(List<String> userIds) {
        LambdaQueryWrapper<H2AppUserBank> wrapper = Wrappers.<H2AppUserBank>lambdaQuery();
        if (CollectionUtils.isNotEmpty(userIds)){
            wrapper.in(H2AppUserBank::getUserId,userIds);
        }
        wrapper.eq(H2AppUserBank::getDeleted,0);
        wrapper.eq(H2AppUserBank::getType,1);
        List<H2AppUserBank> list=list(wrapper);
        return list;
    }
}
